//
//  HSTabBarController.swift
//  HomeSchoolDemo
//
//  Created by 张晓林 on 16/9/26.
//  Copyright © 2016年 张晓林. All rights reserved.
//

import UIKit

class HSTabBarController: UITabBarController {

    // 全局闭包属性
    var leftBtnBlock: (() -> ())?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 
        view.backgroundColor = #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1)
        // 改变按钮字体选中颜色
        tabBar.tintColor = UIColor().colorWithHex(0x00a9e9)
        
        let tabDict = [["vc":"HSMessageController","title":"消息","imageName":"inform"],
                       ["vc":"HSHomeworkController","title":"作业","imageName":"homework"],
                       ["vc":"HSClassroomController","title":"课堂","imageName":"class_exercise"],
                       ["vc":"HSScoreController","title":"成绩","imageName":"examination"]]
        
        // 添加子控制器
        for dict in tabDict {
            addController(dict)
        }
    }
    
    /// 重载添加方法封装
    // fileprivate私有化，支持类延展
    // private 完全私有，只在当前类方法中有效
    fileprivate func addController(_ dict: [String:String]) {
        // 获得命名空间并将控制器名称转换类
       guard let bundName = Bundle.main.bundleName,
               let vcName = dict["vc"],
            let imageName = dict["imageName"],
        // 使用反射机制将字符串转换为类
        let cls = NSClassFromString("\(bundName).\(vcName)") as? UIViewController.Type else {
            return
        }

        // 获得当前类型
        let childController = cls.init()
        // 标题
        childController.title = dict["title"]
        // nomal图片
        childController.tabBarItem.image = UIImage(named: "\(imageName)_nor")
        // 设置字体大小
        childController.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14)], for: .normal)
        // select图片
        childController.tabBarItem.selectedImage = UIImage(named: "\(imageName)_press")?.withRenderingMode(.alwaysOriginal)
        // 添加左边按钮
        
        childController.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "icon_menu_nor", bgImgName: "icon_menu_press", target: self, action: #selector(leftBtnClicked))
        
        // 导航控制器
        let navVc = HSNavigationController(rootViewController: childController)
        // 添加
        addChildViewController(navVc)
    }
    
    /// 左边按钮的监听回调方法
    @objc fileprivate func leftBtnClicked() {
        // 执行闭包，传递点击事件
        leftBtnBlock?()
    }


}

